package cn.liumouren.jzxd.controller;

import cn.liumouren.jzxd.common.utils.PageUtils;
import cn.liumouren.jzxd.common.utils.R;
import cn.liumouren.jzxd.entity.Picture;
import cn.liumouren.jzxd.service.PictureService;
import cn.liumouren.jzxd.utils.QueryUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author Freeman Liu
 * @email llw599502537@gmail.com
 * @date 2020-10-31 00:44:46
 */
@RestController
@RequestMapping("/picture")
@CrossOrigin
@Api(tags = "图片")
public class PictureController {
    @Autowired
    private PictureService pictureService;
    @Resource
    private OSS ossClient;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;
    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    @ApiOperation("万能查询")
    @RequestMapping(value = "/customQuery", method = RequestMethod.GET)
    public R getSceneNames(@RequestParam Map<String, Object> map) {
        PageUtils result = QueryUtil.getResult(pictureService, map);
        return R.ok("查询成功", result);
    }


    /**
     * 列表
     */
    @ApiOperation("分页查询")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = pictureService.queryPage(params);

        return R.ok().put("data", page);
    }


    /**
     * 信息
     */
    @ApiOperation("根据id查询")
    @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
    public R info(@PathVariable("id") String id) {
        Picture picture = pictureService.getById(id);

        return R.ok().put("data", picture);
    }

    /**
     * 保存
     */
    @ApiOperation("新增")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public R save(@RequestBody Picture picture) {
        pictureService.save(picture);

        return R.ok();
    }

    /**
     * 修改
     */
    @ApiOperation("修改")
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public R update(@RequestBody Picture picture) {
        pictureService.updateById(picture);

        return R.ok();
    }

    /**
     * 删除
     */
    @ApiOperation("批量删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public R delete(@RequestBody String[] ids) {
        pictureService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 获取签名
     */
    @ApiOperation("获取签名,上传图片到aliyun oss")
    @GetMapping("/policy")
    public R policy() {
        //host的格式为bucketname.endpoint
        String host = "https://" + bucket + "." + endpoint;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //用户上传文件时指定的前缀
        String dir = sdf.format(new Date()) + "/";

        Map<String, String> respMap;
        String key;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConditions = new PolicyConditions();
            //设置上传文件的大小，这个大小可以自己设定
            policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 10485760); //10M
            //设置保存文件的文件夹
            policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConditions);
            byte[] binaryPolicy = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryPolicy);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            key = UUID.randomUUID() + RandomStringUtils.randomNumeric(5);

            respMap = new LinkedHashMap<>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("key", key);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

        } catch (Exception e) {
            e.printStackTrace();
            return R.error(500, "获取签名失败!");
        }
        String imgUrl = host + "/" + dir + key;
//        foodService.saveImgUrl(host + "/" + dir + key, aid, state);
        // 保存到pic
        Picture picture = new Picture();
        picture.setUrl(imgUrl);
        String id = pictureService.savePic(picture);
        if (id != null) {
            respMap.put("pictureId", id);
        }
        return R.ok("获取签名成功!", respMap);
    }


    @ApiOperation("获取轮播图")
    @RequestMapping(value = "/getCarousels", method = RequestMethod.GET)
    public R getCarousels() {
        List<Picture> pictures = pictureService.getCarousels();
        return R.ok("成功获取" + pictures.size() + "张轮播图", pictures);
    }

}
